package joney.main.utils;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressIndicator;
import org.eclipse.swt.widgets.Label;

 public class ProgressMonitor implements IProgressMonitor 
 {

    private final ProgressIndicator widget;
    private final Label nameLbl;
    private boolean cancelled, indeterminate;

    public ProgressMonitor( ProgressIndicator widget, Label nameLbl , boolean indeterminate) {
      this.widget = widget;
      this.nameLbl = nameLbl;
      this.indeterminate = indeterminate;
    }

    public void beginTask( final String name, final int totalWork ) {
      asyncExec( new Runnable() {

        public void run() {
          if( !widget.isDisposed() ) {
            setFeedbackText( name );
           
            
            if(indeterminate)
            	widget.beginAnimatedTask();
            else
            	widget.beginTask( totalWork );
          }
        }
      } );
    }

    private void asyncExec( Runnable runnable ) {
      if( !widget.isDisposed() ) {
        widget.getDisplay().asyncExec( runnable );
      }
    }

    /** must be called from within the UI thread */
    protected void setFeedbackText( String name ) {
      nameLbl.setText( name );
      nameLbl.getParent().layout();
    }

    public void done() {
      asyncExec( new Runnable() {

        public void run() {
          if( !widget.isDisposed() ) {
            widget.done();
          }
        }
      } );
    }

    public void internalWorked( double work ) {
      throw new UnsupportedOperationException( "Matthias wants to see when this is called" );
    }

    public boolean isCanceled() {
      return cancelled;
    }

    public void setCanceled( boolean cancelled ) {
      this.cancelled = cancelled;
    }

    public void setTaskName( final String name ) {
      asyncExec( new Runnable() {

        public void run() {
          if( !widget.isDisposed() ) {
            setFeedbackText( name );
          }
        }
      } );
    }

    public void subTask( String name ) {
    	setTaskName(name);
    }

    public void worked( final int work ) {
      asyncExec( new Runnable() {

        public void run() {
          if( !widget.isDisposed() ) {
            widget.worked( work );
          }
        }
      } );
    }
  }
